const { ipcMain, BrowserWindow } = require('electron')

_capture = (url, mainWindow) => {
  const offscreenWindow = new BrowserWindow({
    width: 500,
    height: 500,
    show: false,
    webPreferences: {
      offscreen: true,
      contextIsolation: true
    }
  })

  offscreenWindow.loadURL(url)

  offscreenWindow.webContents.on('did-finish-load', () => {
    let title = offscreenWindow.getTitle()

    offscreenWindow.webContents.capturePage().then((image) => {
      let screenshot = image.toDataURL()
      mainWindow.webContents.send('new-item', {
        title,
        screenshot,
        url
      })
      offscreenWindow.close()
    })
  })
}

exports.capture = (mainWindow) => {
  ipcMain.on('new-url', (e, args) => {
    _capture(args._value, mainWindow)
  })
}